﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Lm.Common.ExtensionMethods;

namespace Lm.Common.Auth.Token
{
    [Operation.Operation("{F2D910AB-89D4-44EF-AC1F-BC0ED313BB28}", "临时授权管理员", "")]
    public class TempAuthorizeAdmin:Operation.OperationBase
    {
        static TempAuthorizeAdmin()
        { Operation.OperationBase.CreateOperation(typeof(TempAuthorizeAdmin)); }

        public TempAuthorizeAdmin(string token)
            : base(token)
        { }

        public List<Model.Token> GetAuthorizeList(params System.Linq.Expressions.Expression<Func<Model.Token, bool>>[] conditions)
        {
            if (this.Token.OwnerAccount != this.Token.OperatorAccount)
            { throw new Exception("使用他人临时授权登录时，不能查询临时授权"); }
            var conditionList = conditions.ToList();
            
            conditionList.Add(t => t.OwnerAccount != t.OperatorAccount);
            return DAL.DALFactory.Create().Select<Model.Token>(conditionList.ToArray());
        }

        public void StopAuthorize(string userToken)
        {
            if (this.Token.OwnerAccount != this.Token.OperatorAccount)
            { throw new Exception("使用他人临时授权登录时，不能终止临时授权"); }

            if (userToken.IsNullOrBlank())
            { throw new Exception("必输输入要终止的临时授权Token"); }

            using (var tran = new System.Transactions.TransactionScope())
            {
                var helper = DAL.DALFactory.Create();
                if (helper.IsSingle<Model.Token>(t => t.UserToken == userToken) == false)
                { throw new Exception("token不存在"); }
                var token = helper.GetSingle<Model.Token>(t => t.UserToken == userToken);
              
                if (token.OwnerAccount == token.OperatorAccount)
                { throw new Exception("只能终止临时授权Token"); }
                if (token.ExpireTime < DateTime.Now)
                { throw new Exception("Token已过期，无需终止"); }
                token.ExpireTime = DateTime.Now.AddDays(-1);
                if (helper.Update<Model.Token>(token, t => t.Id == token.Id) != 1)
                { throw new Exception("终止临时授权失败"); }
                tran.Complete();
            }
        }

    }
}
